import tkinter
from pathlib import Path
from tkinter import *
import requests
import re
from tkinter import filedialog
import os
import sys

from nb.com.ui.Constant import PicConstant

picconstant = PicConstant(os.path.dirname(os.path.abspath(__file__)))

def open_file():
    picconstant = PicConstant(filedialog.askopenfilename())

def dowmloadPic(html, keyword):
    fullFilepath=picconstant.picsaveurl+os.sep+"config.config"
    my_file = Path(fullFilepath)
    savefilefolder=None
    if my_file.is_file():
        file = open(fullFilepath, "r");
        lines = file.readlines();
        file.close();
        first_line = lines[0];
        print(first_line);
        savefilefolder=first_line
    else:
        print("文件不存在")
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    for each in pic_url:

        consoleText.insert(END, '正在下载第' + str(i) + '张图片，图片地址:' + str(each) + "\n")
        try:
            pic = requests.get(each, timeout=10)
        except requests.exceptions.ConnectionError:

            consoleText.insert(END, '【错误】当前图片无法下载'+ str(each) + "\n")
            continue



        dir = savefilefolder+os.sep  + '_' + str(i) + '.jpg'
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        i += 1

def on_search_button_click():
    content = searchText.get('1.0', END)
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + content + '&ct=201326592&v=flip'
    result = requests.get(url)
    dowmloadPic(result.text, content)

def about():
    consoleText.insert(END, "关于" + "\n")

def checkupdate():
    consoleText.insert(END, "检查更新" + "\n")

def setconfig():
    consoleText.insert(END, "设置" + "\n")
    get_open_path = tkinter.filedialog.askdirectory(title = "选择要保存文件的路径")
    print("选择的文件路径为-> ",get_open_path)
    createConfigFile(get_open_path)
def createConfigFile(get_open_path):
    fullFilepath=picconstant.picsaveurl+os.sep+"config.config"
    if os.path.exists(picconstant.picsaveurl):
        file=open(fullFilepath,"w")
        file.write(get_open_path);
        file.close();
    else:
        os.mkdir(picconstant.picsaveurl)
        file=open(fullFilepath,"w")
        file.write(get_open_path);
        file.close();






root = Tk()
root.geometry('350x250')

toobar = Menu(root, tearoff=False)
toobar.add_cascade(label="关于", command=about)
toobar.add_cascade(label="检查更新", command=checkupdate)
toobar.add_cascade(label="设置", command=setconfig)
root['menu'] = toobar

frame = Frame(root, highlightbackground="grey", highlightthickness=1)
frame.pack()

searchText = Text(frame, width=15, height=1)
# 样式sunken为凹形，背景为白色，伪装为一个文本框
searchText.grid(column=0, row=0)

# 创建按钮组件
button = Button(frame, text="点击搜索")
button.grid(column=1, row=0)
button.config(command=on_search_button_click)

frame2 = Frame(root, highlightbackground="grey", highlightthickness=1)
frame2.pack()

scroll=Scrollbar(root,orient='vertical')
scroll.pack(side="right",fill="y")
#scroll.grid(row=0, column=1, sticky="ns")
consoleText = Text(frame2, width=50, height=10)
consoleText.config(yscrollcommand=scroll.set)
consoleText.insert(END, "")
consoleText.grid(row=3, column=0)


scroll.config(command=consoleText.yview())


# 运行主循环
root.mainloop()
